﻿using CQIE.TES.IDAL;
using CQIE.TES.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CQIE.TES.WEB.USER.Models;

namespace CQIE.TES.DAL
{
    public class QuestionDAL: DALBase<Question>,IQuestionDAL
    {
        public IList<Question> GetAllDemo()
        {
            using (MyDB db = new MyDB())
            {
                var list = db.Question.ToList();

                return list;
            }
        }

        /// <summary>
        /// 获取问卷
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public Question GetQuestion(ENUM_EVA_TYPE type)
        {
            using (MyDB db = new MyDB())
            {
                Question data;
                if (type == ENUM_EVA_TYPE.Student)
                {
                    data = db.Question.Include(r => r.Children).FirstOrDefault(r => r.Info == "学生方面");
                }

                else if (type == ENUM_EVA_TYPE.Department)
                {
                    data = db.Question.Include(r => r.Children).FirstOrDefault(r => r.Info == "系部方面");
                }

                else if (type == ENUM_EVA_TYPE.CourseLeader)
                {
                    data = db.Question.FirstOrDefault(r => r.Info == "教研室方面");
                }

                else if (type == ENUM_EVA_TYPE.Teacher)
                {
                    data = db.Question.FirstOrDefault(r => r.Info == "同行方面");
                }

                else
                {
                    data = db.Question.FirstOrDefault(r => r.Info == "教师个人方面");
                }

                GetChildren(data.Children);

                return data;
            }
        }

        public bool ChangeHeight(int mode, List<int> questionList, List<int> heightList)
        {

            // 处理heightList
            int total = 0;
            heightList.ForEach(r=>total+=r);
            List<double> height = heightList.Select(r => Math.Round((double) (r/total),2)).ToList();

            using (MyDB db = new MyDB())
            {
                for (int i = 0; i < questionList.Count; i++)
                { 
                    db.Question.Find(questionList[i]).Height= height[i];
                }

                if (db.SaveChanges()==0)
                {
                    return false;
                }

                return true;
            }
        }


        /// <summary>
        /// 递归读取所有叶节点
        /// </summary>
        /// <param name="query"></param>
        private void GetChildren(ICollection<Question> query)
        {
            foreach (Question question in query)
            {
                if (question.Children.Count > 0)
                {
                    GetChildren(question.Children);
                }
                
            }
            
        }

    }
}
